package com.audaque.springboot.foshanupload.sessionvalid.filter;


import cn.hutool.core.bean.BeanUtil;
import com.audaque.springboot.foshanupload.authcore.constants.AuthConst;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;


@Slf4j
public class SessionFilter implements Filter {



    private String[] excludedUris;


    public void init(FilterConfig filterConfig) throws ServletException {
        String param = filterConfig.getInitParameter("excludedUris");//获取参数值
        if (StringUtils.isNotBlank(param)) {
            this.excludedUris = param.split(",");
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest= (HttpServletRequest) request;
        HttpServletResponse httpServletResponse= (HttpServletResponse) response;


        //spring session负责创建sessionId，不用开发者处理
        HttpSession session = httpServletRequest.getSession();
        //没有则放行
        if (session == null) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        String sessionId = session.getId();
        //有状态
        Object attribute = session.getAttribute(AuthConst.CURRENT_USER_KEY);
        if (attribute != null) {
            TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = BeanUtil.toBean(attribute, TransmittableThreadLocalCurrentUser.class);
            String sessionId1 = transmittableThreadLocalCurrentUser.getSessionId();
            if(Objects.equals(sessionId,sessionId1)){
                //添加当前用户到上下文
                TransmittableThreadLocalCurrentUser.setCurrentUser(transmittableThreadLocalCurrentUser);
            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
        return;
    }

}
